package de.koller.worlders.engine.tiles.data;

import de.koller.oceanFramework.util.MIn;
import de.koller.oceanFramework.util.MOut;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MapDetails {
	
	private final String path;
	private final MapData mapData;
	
	private final Set<DetailEntity> detail = new HashSet<>();

	public MapDetails( MapData mapData ) {
		this.mapData = mapData;
		path = mapData.getPrePath() + mapData.getName() + "_details.2mw";
		load();
	}
	
	private void load() {
		MIn i = new MIn( path );
		
		byte s = i.read( 1 )[0];
		
		while( s != 0 ) {
			loadDetail( i, s );
			s = i.read( 1 )[0];
		}
		
		i.close();
	}

	public void save() {
		MOut o = new MOut( path );
		
		for( DetailEntity mld : detail )
			saveDetails( mld, o );
		
		o.close();
	}
	
	private void saveDetails( DetailEntity mld, MOut o ) {
		o.write( mld.id );
		o.writeInt( mld.x );
		o.writeInt( mld.y );
		
		byte[] n = mld.content.getBytes();
		o.writeInt( n.length );
		o.write( n );
	}
	
	private void loadDetail( MIn i, byte id ) {
		int x = i.readInt( 1 )[0];
		int y = i.readInt( 1 )[0];
		int si = i.readInt( 1 )[0];
		String n = new String( i.read( si ) );
		addDetail( id, x, y, n );
	}

	public void addDetail( IDEntity id, int x, int y, String name ) {
		this.addDetail( id.getId(), x, y, name );
	}
	
	public void addDetail( byte id, int x, int y, String name ) {
		DetailEntity mld = new DetailEntity();
		mld.id = id;
		mld.x = x;
		mld.y = y;
		mld.content = name;
		detail.add( mld );
	}
	
	public void removeDetail( IDEntity id, int x, int y ) {		
		Set<DetailEntity> tr = new HashSet<>();
		for( Iterator<DetailEntity> i = detail.iterator(); i.hasNext(); ) {
			DetailEntity m = i.next();
			if( m.id == id.getId() && m.x == x && m.y == y )
				tr.add( m );
		}
		detail.removeAll( tr );
	}
	
	public DetailEntity getDetail( IDEntity id, int x, int y ) {
		for( Iterator<DetailEntity> i = detail.iterator(); i.hasNext(); ) {
			DetailEntity m = i.next();
			if( m.id == id.getId() && m.x == x && m.y == y )
				return m;
		}
		
		return null;
	}

	public enum IDEntity {
		MapLeave( (byte)1 ),
		HelpTile( (byte)2 );
		
		private final byte id;

		private IDEntity( byte id ) {
			this.id = id;
		}

		public byte getId() {
			return id;
		}
		
	}
	
	public class DetailEntity {
		public int x;
		public int y;
		public byte id;
		public String content;
	}

}
